package com.example.filter;

import com.example.holder.TenantHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author wangy
 * @create 2021/7/12 17:18
 * @Description 拦截器拦截域名前缀，来实现访问独有数据库
 */
@Component
@WebFilter(urlPatterns = "/**")
public class TenantHolderFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(TenantHolderFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        log.info("+++++++++++++请求路径:[=>{}<=]+++请求时间:[{}]++++++++++++++++++++++++", request.getRequestURL(), LocalDateTime.now());
        String host = request.getHeader("Host");
        log.info("处理请求的线程是:[{}],host是:[{}]", Thread.currentThread().getName(), host);
        String tenantCode = host.split("\\.")[0];
        //设置tenant
        TenantHolder.setTenantCode(tenantCode);
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            //异常处理
            log.info("{}", e.getMessage());
        } finally {
            //移除tenant
            TenantHolder.remove();
        }
    }

}
